// websocket.js
import {
    getToken
} from './auth'

class WebSocketClient {
    constructor(url, type) {
        this.url = url;
        this.socket = null;
    }

    connect() {
        if (!getToken('Token')) return;
        this.socket = new WebSocket(this.url + `?user_id=${JSON.parse(localStorage.getItem("user")||'{}').user_id}`);
        this.socket.onopen = this.onOpen.bind(this);
        this.socket.onmessage = this.onMessage.bind(this);
        this.socket.onclose = this.onClose.bind(this);
        this.socket.onerror = this.onError.bind(this);
    }

    onOpen(event) {

    }

    onMessage(event) {

    }

    onClose(event) {
        if (getToken('Token')) this.connect()
    }

    onError(error) {
        console.error('WebSocket error:', error);
    }

    send(message) {
        if (this.socket.readyState !== WebSocket.OPEN) {
            console.warn('WebSocket not open, message not sent:', message);
            return;
        }
        this.socket.send(message);
    }

    close() {
        this.socket.close();
    }
}

export default WebSocketClient;
